package com.lkc.service.impl;

import com.lkc.annotation.LogMethod;
import com.lkc.bean.Users;
import com.lkc.mapper.UsersDao;
import com.lkc.service.UsersService;
import com.lkc.util.Page;
import com.lkc.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
@Service

public class UsersServiceImpl implements UsersService {
    @Autowired
    UsersDao usersDao;

    @Override
    @LogMethod(serviceName = "用户服务", recordParam = true, recordReturn = true)
    public Users add(Users users) {
        // 对密码进行加密处理
        if (users.getPassword() != null && !users.getPassword().isEmpty()) {
            users.setPassword(PasswordUtil.getEncryption(users.getPassword()));
        }

        //新增数据
        usersDao.add(users);
        //通过主键查询数据库中的数据
        usersDao.one(users.getUserId());
        Users result=usersDao.one(users.getUserId());
        return result;
    }

    @Override
//    @CacheEvict(value = "users",key = "#p0",allEntries = true)
    @LogMethod(serviceName = "用户服务", recordParam = true, recordReturn = true)
    public int del(Integer userId) {
        return usersDao.del(userId);
    }

    @Override
//    @CachePut(value = "users",key = "#p0.userId")
    @LogMethod(serviceName = "用户服务", recordParam = true, recordReturn = true)
    public Users edit(Users users) {
        // 如果密码不为空，则进行加密处理
        if (users.getPassword() != null && !users.getPassword().isEmpty()) {
            users.setPassword(PasswordUtil.getEncryption(users.getPassword()));
        } else {
            // 如果密码为空，不更新密码字段
            users.setPassword(null);
        }

        usersDao.edit(users);
        Users result=usersDao.one(users.getUserId());
        System.out.println(users);

        return result;
    }

    @Override
    @LogMethod(serviceName = "用户服务", recordParam = true, recordReturn = false)
    public List<Users> all(Users users) {
        return usersDao.all(users);
    }

//    @Cacheable(value = "users",key = "#p0")
    @Override
    @LogMethod(serviceName = "用户服务", recordParam = true, recordReturn = true)
    public Users one(Integer userId) {
        return usersDao.one(userId);
    }

    @Override
    @LogMethod(serviceName = "用户服务", recordParam = true, recordReturn = false)
    public void page(Page page, Users users) {
        int count=usersDao.pageCount(users);
        Object data=usersDao.page(page,users);
        page.setCount(count);
        page.setData(data);
    }
}
